﻿using AspSQLProvider;
using Ext.Net;
using Ext.Net.MVC;
using PcaCore.BOL.Pca;
using PcaCore.DAL.Pca;
using PcaWeb.Areas.Admin.Models;
using PcaWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace PcaWeb.Areas.Admin.Controllers
{
    [DirectController(AreaName="Admin")]
    public class UsuariosController : ControllerAdmin
    {
        public IMembershipService membershipService { get; set; }

        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            if (membershipService == null) { membershipService = new MembershipService(); }

            base.Initialize(requestContext);
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetListUsuarios(StoreRequestParameters parameters)
        {
            int total;
            List<PgMembershipUser> usersCollection = membershipService.GetAllUsers(parameters.Start, parameters.Limit, out total);
            return this.Store(usersCollection, total);
        }

        public Ext.Net.MVC.PartialViewResult FrmRegistrar()
        {            
            return new Ext.Net.MVC.PartialViewResult
            {
                ViewName = "FrmRegistrar"
            };
        }

        public Ext.Net.MVC.PartialViewResult FrmEditar(string userName)
        {
            PgMembershipUser user = membershipService.Get(userName);
            ViewBag.activo = user.IsApproved;

            RegisterModel model = new RegisterModel();
            model.RegisterUserName=user.UserName;
            model.RegisterEmail=user.Email;
            model.RegisterPassword = "00000000000000";//asignamos para pasar "ModelState.IsValid"
            model.RegisterConfirmPassword = "00000000000000";//asignamos para pasar "ModelState.IsValid"
            model.RegisterNick=user.nick;
            model.RegisterNombre=user.nombre;
            model.RegisterApellido=user.apellido;
            model.RegisterZonaHoraria = user.zonaHorariaId;

            return new Ext.Net.MVC.PartialViewResult
            {
                ViewName = "FrmEditar",
                Model = model,
                ViewData = ViewData
            };
        }

        public Ext.Net.MVC.PartialViewResult FrmCambiarPassword(string userName)
        {
            ChangePasswordUserModel model = new ChangePasswordUserModel();
            model.UserName = userName;

            return new Ext.Net.MVC.PartialViewResult
            {
                ViewName = "FrmCambiarPassword",
                Model = model
            };
        }

        public Ext.Net.MVC.PartialViewResult FrmAsignarOficinas(string userName)
        {
            ViewBag.userName = userName;

            return new Ext.Net.MVC.PartialViewResult
            {
                ViewName = "FrmAsignarOficinas",
                ViewData = ViewData
            };
        }

        public Ext.Net.MVC.PartialViewResult FrmEditarRoles(string userName)
        {
            ViewBag.userName = userName;

            return new Ext.Net.MVC.PartialViewResult
            {
                ViewName = "FrmEditarRoles",
                ViewData = ViewData
            };
        }

        [HttpPost]
        public ActionResult RegistrarUsuario(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                MembershipCreateStatus createStatus = membershipService.CreateUser(model.RegisterUserName, model.RegisterPassword, model.RegisterEmail, model.RegisterNick, model.RegisterNombre, model.RegisterApellido, model.RegisterZonaHoraria);

                if (createStatus == MembershipCreateStatus.Success)
                    return Json(new { success = true });
                else
                    return Json(new { success = false, msg = MembershipValidation.ErrorCodeToString(createStatus) });
            }
            return Json(new { success = false, msg = "No se envio informacion correctamente." });
        }

        [HttpPost]
        public ActionResult ActualizarUsuario(RegisterModel model, string activo)
        {
            try
            {
                bool _activo = string.IsNullOrEmpty(activo) ? false : true;
                if (ModelState.IsValid)
                {
                    membershipService.UpdateUser(model.RegisterUserName, model.RegisterEmail, _activo, model.RegisterNick, model.RegisterNombre, model.RegisterApellido, model.RegisterZonaHoraria);
                    return Json(new { success = true });
                }
                return Json(new { success = false, msg = "No se envio informacion correctamente." });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }
        }

        [HttpPost]
        public ActionResult CambiarPassword(ChangePasswordUserModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (membershipService.ChangePassword(model.UserName, model.NewPassword))
                        return Json(new { success = true });
                    else
                        return Json(new { success = false, msg = "Error al actualizar password." });
                }
                return Json(new { success = false, msg = "No se envio informacion correctamente." });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }
        }

        public ActionResult ConfirmarEliminarUsuario(string userName)
        {
            try
            {
                MessageBoxConfig config = new MessageBoxConfig();
                config.Title = "Confirmacion";
                config.Message = string.Format("Eliminar usuario {0}", userName);
                config.Closable = false;
                config.Icon = MessageBox.Icon.QUESTION;
                config.Buttons = MessageBox.Button.YESNO;
                config.MessageBoxButtonsConfig = new MessageBoxButtonsConfig
                {
                    Yes = new MessageBoxButtonConfig { Handler = string.Format("Usuarios.Admin.EliminarUsuario(\"{0}\")", userName), Text = "Si" },
                    No = new MessageBoxButtonConfig { Text = "No" }
                };

                X.Msg.Show(config);
                return this.Direct();

                
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }
        }

        [DirectMethod(Namespace="Usuarios")]
        public ActionResult EliminarUsuario(string userName)
        {
            try
            {
                if (membershipService.DeleteUser(userName))
                {
                    this.GetCmp<Store>("storeUsuarios").Reload();
                    return this.Direct();
                }
                else
                {
                    return Json(new { success = false, msg = "No se pudo eliminar el usuario, consulte al administrador para mas información." });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }
        }

        [DirectMethod(Namespace="Usuarios")]
        public ActionResult AsignarRol(string userName, string rolName, bool asignar)
        {
            try
            {
                if (asignar)
                    Roles.AddUserToRole(userName, rolName);
                else
                    Roles.RemoveUserFromRole(userName, rolName);

                return this.Direct(new { success = true });
            }
            catch (Exception ex)
            {
                return this.Direct(new { success = false, msg = ex.Message });
            }
        }

        [DirectMethod(Namespace = "Usuarios")]
        public ActionResult AsignarOficina(string userName, string nodeId, bool asignar)
        {
            try
            {
                string usuarioId = membershipService.Get(userName).ProviderUserKey.ToString();
                string[] nodeCodes = nodeId.Split(new char[] { '-' });
                string empresaId = null;
                string oficinaId = null;
                
                
                if (nodeCodes.Length == 2)
                {
                    empresaId = nodeCodes[0];
                    oficinaId = nodeCodes[1];
                    
                    if (asignar)
                        dUsuario.Insert(new oUsuario { empresa_id = empresaId, oficina_id = oficinaId, usuario_id = usuarioId });
                    else
                        dUsuario.Delete(empresaId, oficinaId, usuarioId);

                    return this.Direct(new { success = true });
                }
                else
                {
                    return this.Direct(new { success = false, msg = "nodeId no tiene el formato correcto" });
                }
            }
            catch (Exception ex)
            {
                return this.Direct(new { success = false, msg = ex.Message });
            }
        }

        public ActionResult RunCommandGrid(string commandName, string userName)
        {
            switch (commandName)
            {
                case "cmdEditar":
                    return FrmEditar(userName);
                case "cmdCambiarPassword":
                    return FrmCambiarPassword(userName);
                case "cmdEliminar":
                    return ConfirmarEliminarUsuario(userName);
                case "cmdEditarRoles":
                    return FrmEditarRoles(userName);
                case "cmdAsignarOficina":
                    return FrmAsignarOficinas(userName);
                default:
                    return Json(new { success = false, msg = String.Format("\"{0}\" no es un comando valido", commandName) });
            }
        }

        public StoreResult GetListEmpresas(string userName, string node)
        {
            NodeCollection nodes = new NodeCollection();
            List<oEmpresa> empresas = dEmpresa.GetList();
            List<oOficina> oficinas;
            List<oVwUsuarioEmpresa> oficinasAsignadas;//la lista de empresas que tiene asignado el usuario
            Node nodeItem = null;
            string usuarioId = membershipService.Get(userName).ProviderUserKey.ToString();

            if (!string.IsNullOrEmpty(node))
            {
                if (node == "0")//Cargamos empresas
                {
                    foreach (oEmpresa item in empresas)
                    {
                        nodeItem = new Node();
                        nodeItem.Text = item.nombre;
                        nodeItem.NodeID = item.empresa_id;
                        nodeItem.Leaf = false;
                        nodes.Add(nodeItem);
                    }
                }
                else//cargamos las oficinas
                {
                    
                    oficinas = dOficina.GetList(node);
                    oficinasAsignadas = dUsuario.GetListOficinas(usuarioId, node);

                    foreach (oOficina item in oficinas)
                    {
                        nodeItem = new Node();
                        nodeItem.Text = item.nombre;
                        nodeItem.NodeID = string.Format("{0}-{1}", item.empresa_id, item.oficina_id);
                        nodeItem.Leaf = true;
                        nodeItem.Checked = false;

                        foreach(oVwUsuarioEmpresa oficina in oficinasAsignadas)
                        {
                            if (oficina.empresa_id == item.empresa_id && oficina.oficina_id == item.oficina_id)
                            {
                                nodeItem.Checked = true;
                                oficinasAsignadas.Remove(oficina);
                                break;
                            }
                        }
                        
                        nodes.Add(nodeItem);
                    }
                }
            }

            return this.Store(nodes);
        }

    }
}
